package com.qingcheng.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.*;
import java.util.*;

@Component
public class PageUtil {

    @Value("${pagePath}")
    private String pagePath;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 创建页面
     * @param mapJsonString
     */
    public void createPage(String mapJsonString){
        //1.查询商品详情
        Map<String, Object> mapJson = (Map<String, Object>)JSON.parseObject(mapJsonString);
        Goods goods = JSON.parseObject(JSON.toJSONString(mapJson.get("goods")),Goods.class);
        //获取SPU信息
        Spu spu = goods.getSpu();
        //获取SKU列表
        List<Sku> skuList = goods.getSkuList();
        //商品分类
        List<String> categoryList = (List<String>)mapJson.get("categoryList");

        //创建SKU地址列表
        Map urlMap = new HashMap();
        for(Sku sku:skuList){
            if(sku.getStatus().equals("1")){
                //对规格json字符串进行排序 需要对字符串进行排序，保证tojSonSting，不会出错
                String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField) ;
                urlMap.put(specJson,sku.getId()+".html");
//            urlMap.put(sku.getSpec(),sku.getId()+".html"); 需要对字符串进行排序，保证tojSonSting，不会出错
            }
        }

        //2.创建页面
        for(Sku sku:skuList){ //遍历sku
            //1.创建上下文
            Context context = new Context();
            //创建数据模型
            Map<String,Object> dataModel = new HashMap();
            dataModel.put("spu",spu);
            dataModel.put("sku",sku);
            dataModel.put("categoryList",categoryList);
            dataModel.put("spuImages",spu.getImages().split(","));//spu图片列表
            dataModel.put("skuImages",sku.getImages().split(","));//sku图片列表

            Map paraItems = JSON.parseObject(spu.getParaItems());//spu参数列表
            dataModel.put("paraItems",paraItems);

            Map<String,String> specItems = (Map)JSON.parseObject(sku.getSpec());//sku规格列表
            dataModel.put("specItems",specItems);

            //规格选择面板 {"颜色":["天空之境","珠光贝母"],"内存": ["8GB+64GB","8GB+128GB","8GB+256GB"]}
            //{"颜色":[{"option":"天空之境","checked":"true"},{"option":"珠光贝母","checked":"false"}],"内存": [{},{},{}]}
            Map<String,List> specMap = (Map)JSON.parseObject(spu.getSpecItems());
            for(String key:specMap.keySet()){//循环规格
                List<String> list = specMap.get(key);//["天空之境","珠光贝母"] 旧的集合
                List<Map> mapList = new ArrayList<Map>();//新的集合，用来替换旧的集合 [{"option":"天空之境","checked":"true"},{"option":"珠光贝母","checked":"false"}]
                for(String value:list){
                    Map map = new HashMap();
                    map.put("option",value);
                    if(specItems.get(key).equals(value)){ //如果和当前的sku规格一致，那就是选中
                        map.put("checked","true");//是否选中
                    }else{
                        map.put("checked","false");//是否选中
                    }

                    Map<String,String> spec = (Map)JSON.parseObject(sku.getSpec());
                    spec.put(key,value);//感觉这步是覆盖加添加对于了，保证每个sku循环下来，有不同的url
                    String specJson = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    map.put("url",urlMap.get(specJson));

//                    System.out.println(sku.getSpec());//可以直接取sku.getSpec(),会导致整个sku循环下来所有的改变都指向同一个url(sku.getSpec());
//                    map.put("url",urlMap.get(sku.getSpec()));//这是错误的，要保证每个sku渲染的页面有不同的url
//                    System.out.println("map.url:"+map.get("url"));

                    mapList.add(map);
                }
                //旧的集合，替换新的集合
                specMap.put(key,mapList);
            }

            dataModel.put("specMap",specMap);

            context.setVariables(dataModel);

            //2.准备文件
            File dir = new File(pagePath);
            if(!dir.exists()){
                dir.mkdirs();
            }

            File dest = new File(dir,sku.getId()+".html");

            //3.生成页面
            try {
                PrintWriter writer = new PrintWriter(dest,"UTF-8");
                templateEngine.process("item",context,writer);
                System.out.println(sku.getId()+".html");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 删除页面
     * @param mapJsonString
     */
    public void deletePage(String mapJsonString){

        //1.查询商品详情
        Map<String, Object> map = (Map<String, Object>)JSON.parseObject(mapJsonString);
        Goods goods = JSON.parseObject(JSON.toJSONString(map.get("goods")),Goods.class);
        //获取SPU信息
        Spu spu = goods.getSpu();
        //获取SKU列表
        List<Sku> skuList = goods.getSkuList();

        //删除SKU页面所在文件
        for(Sku sku:skuList){
            if(sku.getStatus().equals("2")){ //为下架商品
                String path=pagePath+sku.getId()+".html";//此商品的具体地址
                File file = new File(pagePath);
                if(file.exists()){
                    file.delete();
                }
            }
        }

    }
}
